package com.roin.learn.activiti.controller;

import com.roin.learn.activiti.base.BaseController;
import com.roin.learn.activiti.base.SysConstent;
import com.roin.learn.activiti.entity.ResourceResult;
import com.roin.learn.activiti.exception.BusinessException;
import com.roin.learn.activiti.service.ProcessService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * 流程实例业务Controller
 */
@RequestMapping("process/instance")
@Controller
public class ProcessInstanceController extends BaseController{
    @Resource
    ProcessService processService;
    @Resource
    RuntimeService runtimeService;
    @Resource
    HistoryService historyService;
    /**
     * 转到流程实例列表页面
     * @return
     */
    @RequestMapping("")
    public ModelAndView toInstance(){
        ModelAndView mav = new ModelAndView("process/instance");
        List<ProcessInstance> instances = processService.getProcessInstanceList(null);
        mav.addObject("instances",instances);
        return mav;
    }
    /**
     *挂起或激活流程实例
     * @param processInstanceId 流程空间实例ID
     * @param suspendOrActivate 挂起还是激活，suspend挂起，activate激活
     * @return
     */
    @RequestMapping("suspendOrActivate.do")
    @ResponseBody
    public ResourceResult suspendOrActivate(String processInstanceId,String suspendOrActivate){
        ResourceResult result = new ResourceResult();
        try {
            checkLogin();
            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if (instance==null)
                throw new BusinessException("此流程实例不存在或流程已经结束！");
            if ("suspend".equals(suspendOrActivate)){
                if (instance.isSuspended()){
                    throw new BusinessException("此流程实例已为挂起状态，不需要挂起！");
                }else {
                    runtimeService.suspendProcessInstanceById(processInstanceId);
                    result.setSuccess(true).setMessage("挂起成功！");
                }
            }

            else if ("activate".equals(suspendOrActivate)){
                if (!instance.isSuspended()){
                    throw new BusinessException("此流程实例已为激活状态，不需要激活！");
                }else{
                    runtimeService.activateProcessInstanceById(processInstanceId);
                    result.setSuccess(true).setMessage("激活成功！");
                }
            }

            else {
                throw new BusinessException("suspendOrActivate必须为'suspend'和'activate'中的一个！");
            }
        } catch (BusinessException e) {
            result.setMessage(e.getMessage());
        } catch (Exception e){
            log.error("挂起流程实例异常",e);
            result.setMessage(SysConstent.MSG_SYS_ERROR);
        }
        return result;
    }
    /**
     * 转到流程实例列表页面
     * @return
     */
    @RequestMapping("viewHistory.htm")
    public ModelAndView viewHistory(String processInstanceId,@RequestParam(required = false) String assignee){
        ModelAndView mav = new ModelAndView("process/instanceHistory");
        try {
            List<Task> tasks = processService.queryTaskProcessInstanceId(processInstanceId,null);
            mav.addObject("tasks",tasks);
            List<HistoricActivityInstance> historys = processService.getHistoricActivityInstance(processInstanceId,null);
            mav.addObject("historys",historys);
            mav.addObject("processInstanceId",processInstanceId);
        } catch (Exception e) {
            mav.addObject(ERROR, SysConstent.MSG_SYS_ERROR);
            log.error("查询任务异常",e);
        }
        return mav;
    }

    /**
     * 删除流程实例
     * @param id ProcessInstanceId
     * @return
     */
    @RequestMapping("delete.do")
    @ResponseBody
    public ResourceResult deleteProcessInstance(@RequestParam("id") String id, @RequestParam(required = false,defaultValue = "false") Boolean cascade) {
        ResourceResult result = new ResourceResult();
        runtimeService.deleteProcessInstance(id, "delete");
        if (cascade)
            historyService.deleteHistoricProcessInstance(id);
        result.setSuccess(true).setMessage("删除成功！");
        return result;
    }
}
